<?php
/**
 * Created by PhpStorm.
 * User: chen
 * Date: 2015/12/2
 * Time: 15:28
 */
class IndexAction extends CommAction{
    public function index(){
        //接入验证
        if($_GET['echostr']){
            echo $_GET['echostr'];
            exit;
        }
        $token = M('wechat_plat')->where(array('id'=>1))->getField('token');
        import('@.ORG.Net.Wechat'); // 导入工具类
        $options = array(
            'token' => $token, //填写设定的key
        );
        $Wechat = new Wechat($options);

        //回复变量声明
        $content = null;
        $data = null;
        //获取微信服务器发来的消息类型
        $type = $Wechat->getRev()->getRevType();

        //记录所有非事件推送记录
        if($type!='event'){
            $this->saveMsg($Wechat);
        }
        $openid = $Wechat->getRevFrom();
        //记录用户的微信信息
        $this->saveWxUser($openid);

        

        switch ($type) {
            case Wechat::MSGTYPE_TEXT:
                $content = $Wechat->getRevContent();
                //根据关键字查找库中对应的回复
                $data=$this->getRevByContent($content);
                break;
            case Wechat::MSGTYPE_EVENT:

                //记录事件推送信息
                $event = $Wechat->getRevEvent();
                $recordModel=D('EventRecord');
                $event['openid']=$openid;
                $event['createtime']=time();
                $recordModel->data($event)->add();

                //如果是关注或者取消关注事件，到wxuser表更新subscribe字段,
                if($event['event']=='unsubscribe'){
                    D('Wxuser')->where(array('openid'=>$event['openid']))->data(array('subscribe'=>0))->save();
                }elseif($event['event']=='subscribe'){
                    D('Wxuser')->where(array('openid'=>$event['openid']))->data(array('subscribe'=>1))->save();
                }

                switch($event['event']){
                    case 'CLICK':           //点击菜单模拟发送关键字回复
                        $content = $event['eventKey'];
                        $data=$this->getRevByContent($content);
                        break;

                    case 'subscribe':
//                        $eventKey=$event['eventKey'];  //扫码带来的场景值
//                        $data='感谢关注';
                        $data=$this->getRevByContent('guangjixinxi_subscribe');
                        break;

                    case 'SCAN':   //用户已关注时的扫码事件推送
                        break;

                    case 'LOCATION':    //用户自动上报的地理位置事件
                        break;

                    case 'VIEW':        //点击菜单跳转链接
                        $eventKey=$event['eventKey'];  //点击后跳转的URL
                        break;
                }

        }
        if(is_array($data)){
            //回复图文
            $Wechat->news($data)->reply();
        }else{
            //回复文字
            $Wechat->text($data)->reply();
        }

    }

    /**
     * 用户发送的非事件推送信息
     */
    public function saveMsg($Wechat){
        $receive=$Wechat->_receive;
        $data['openid']=$receive['FromUserName'];
        $data['createtime']=time();
        $data['msgType']=$receive['MsgType'];
        $data['content']=$receive['Content'];
        $data['picUrl']=$receive['PicUrl'];
        $data['mediaId']=$receive['MediaId'];
        $data['format']=$receive['Format'];
        $data['recognition']=$receive['Recognition'];
        $data['thumbMediaId']=$receive['ThumbMediaId'];
        $data['locationX']=$receive['Location_X'];
        $data['locationY']=$receive['Location_Y'];
        $data['scale']=$receive['Scale'];
        $data['label']=$receive['Label'];
        $data['title']=$receive['Title'];
        $data['description']=$receive['Description'];
        $data['url']=$receive['Url'];
        $data['msgId']=$receive['MsgId'];
        D('MsgRecord')->data($data)->add();
    }

    /**
     * 记录微信用户信息
     */
    public function saveWxUser($openid){

        $wxModel=D('Wxuser');
        $map=array();
        $map['openid']=$openid;
        $exist=$wxModel->where($map)->find();
        if($exist == NULL){
            //通过接口获取用户微信信息，增加到表wxuser
            $data=$this->getWxInfo($openid);
            $wxModel->data($data)->add();
        }
    }

    /**
     * 根据关键字找出回复的内容
     */
    public function getRevByContent($keyWord){
        $keyModel=D('KeyWord');
        $map=array();
        $map['keyword']=$keyWord;
        $info=$keyModel->where($map)->find();

        //如果是关注回复，找出这条信息
        if($keyWord=='guangjixinxi_subscribe'){
            $info=$keyModel->where(array('special'=>'subscribe'))->find();
        }

        if(empty($info)){
            return '关键字无匹配';
        }else{
            if($info['type']=='new'){      //回复图文
                $thisValue=$info['value'];
                $thisValue=explode(',',$thisValue);
                foreach($thisValue as $key=>$value){
                    $data=array();
                    $newInfo=D('News')->where(array('id'=>$value))->find();
                    $data['Title']=$newInfo['title'];
                    $data['Description']=$newInfo['discription'];
                    $data['PicUrl']=getBaseUrl().__APP__.'/upload/new/'.$newInfo['img'];
                    $data['Url']=$newInfo['linkurl'];
                    $temp[$key]=$data;
                }

            }elseif($info['type']=='text'){     //回复文字

                $temp=$info['value'];

            }elseif($info['type']=='other'){    //其他功能

            }
        }

        //给click加上1
        $info['click']+=1;
        $keyModel->data($info)->save();
        return $temp;
    }

        

        public function sendCustom($openid, $val, $type = 'text'){
            $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $this->getToken();

            if ($type == 'text') {
                $data = '{
        "touser":"' . $openid . '",
        "msgtype":"text",
        "text":
        {
             "content":"' . $val . '"
        }
    }';
            } elseif ($type == 'image') {
                $data = '{
        "touser":"' . $openid . '",
        "msgtype":"image",
        "image":
        {
          "media_id":"' . $val . '"
        }
    }';
            }
            $result=$this->httpPost($url, $data);

        }

        public function httpPost($url, $data){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            return curl_exec($ch);
        }
}